/**
 * request 网络请求工具
 * 更详细的 api 文档: https://github.com/umijs/umi-request
 */
import { extend } from 'umi-request'
import { message } from 'antd'
import Cookies from 'universal-cookie'
import defaultSettings from '../../config/defaultSettings'

message.config({
  maxCount: 1,
})

const cookies = new Cookies()

const TOKEN_KEY = 'auth_token'

/**
 * 异常处理程序
 */

const errorHandler = error => {
  const { response } = error
  const { status } = response
  console.log('error', error)
  if (status === 401) {
    /* eslint-disable no-underscore-dangle */
    window.g_app._store.dispatch({
      type: 'login/logout',
    })
  }

  return response
}
/**
 * 配置request请求时的默认参数
 */

const request = extend({
  prefix: defaultSettings.URL,
  useCache: false,
  // 默认错误处理
  errorHandler,
  // 默认请求是否带上cookie 要改为确保浏览器不在请求中包含凭据，请使用credentials: 'omit'
  credentials: 'omit',
})

// request拦截器, 改变url 或 options.
request.interceptors.request.use((url, options) => {
  // eslint-disable-next-line no-param-reassign
  options.headers = {
    ...options.headers,
    Accept: 'application/json',
    Authorization: cookies.get(TOKEN_KEY) ? `Bearer${cookies.get(TOKEN_KEY)}` : '',
    'Content-Type': 'application/json; charset=utf-8',
  }
  return {
    url,
    options: {
      ...options,
      interceptors: true,
    },
  }
})

/**
 * 4. 基于response interceptors
 */
request.interceptors.response.use(async response => {
  const result = await response.clone().json()
  const auth_token = response.headers.get('auth_Token')
  const token = result.data ? result.data.token : null
  // TODO:
  if (token || auth_token) {
    cookies.set(TOKEN_KEY, token || auth_token, { path: '/' })
  }

  if (result && result.success) {
    if (result.message) {
      message.success(result.message)
    }
  } else {
    message.error(result.message || '请求失败，请联系管理员')
  }

  return response
})

export default request
